package org.game.gobang.client.handler;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import org.game.gobang.client.constant.ClientConstant;
import org.game.result.RestResult;
import org.game.result.RestResultBuilder;
import org.game.result.ResultCode;
import org.game.util.JsonUtil;

import java.util.HashMap;
import java.util.Map;

@Slf4j
public abstract class GobangClientHandler extends SimpleChannelInboundHandler<String> {
    private ChannelHandlerContext context;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        log.info("client received : " + msg);
        RestResult restResult = JsonUtil.formJson(msg, RestResult.class);
        if (msg != null && restResult.getCode().equals(ResultCode.FAIL.getCode())) {
            log.info("server closed connection , so client will close too");
            ctx.channel().closeFuture();
        }
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        context = ctx;
        ClientConstant.ctx = ctx;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        RestResult restResult = JsonUtil.formJson(msg.toString(), RestResult.class);

        this.getClass().getDeclaredMethod(restResult.getMsg(), ChannelHandlerContext.class, Object.class)
                .invoke(this, ctx, restResult.getData());
    }

    protected abstract void allRooms(ChannelHandlerContext ctx, Object value);
    protected abstract void joinRoom(ChannelHandlerContext ctx, Object value);
    protected abstract void click(ChannelHandlerContext ctx, Object value);
    protected abstract void win(ChannelHandlerContext ctx, Object value);
}